// src/context/ProductContext.tsx
import React, { createContext, useState, useCallback } from 'react';
import {
    productService,
    type Product,
    type CreateProductInput, type UpdateProductInput
} from '../api/service/ProductService';

// 定义商品上下文类型
interface ProductContextType {
    products: Product[];
    selectedProduct: Product | null;
    loading: boolean;
    loadingProduct: boolean;
    loadingCreate: boolean;
    loadingUpdate: boolean;
    loadingDelete: boolean;
    error: string | null;
    hasNext: boolean;
    nextCursor: string | null;
    fetchProducts: (limit?: number, cursor?: string) => Promise<void>;
    fetchProductById: (id: number) => Promise<void>;
    createProduct: (input: CreateProductInput) => Promise<boolean>;
    updateProduct: (id: number, input: UpdateProductInput) => Promise<boolean>;
    deleteProduct: (id: number) => Promise<boolean>;
    selectProduct: (product: Product | null) => void;
    clearSelectedProduct: () => void;
    refreshProducts: () => Promise<void>;
    fetchMoreProducts: (limit?: number) => Promise<void>;
    // 添加搜索相关方法和状态
    searchProducts: (keyword: string, limit?: number, cursor?: string) => Promise<void>;
    searchKeyword: string | null;
    isSearching: boolean;
}

// 创建上下文
const ProductContext = createContext<ProductContextType | undefined>(undefined);

// Provider 组件
export const ProductProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [products, setProducts] = useState<Product[]>([]);
    const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
    const [loading, setLoading] = useState<boolean>(false);
    const [loadingProduct, setLoadingProduct] = useState<boolean>(false);
    const [loadingCreate, setLoadingCreate] = useState<boolean>(false);
    const [loadingUpdate, setLoadingUpdate] = useState<boolean>(false);
    const [loadingDelete, setLoadingDelete] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);
    const [hasNext, setHasNext] = useState<boolean>(false);
    const [nextCursor, setNextCursor] = useState<string | null>(null);
    // 添加搜索相关状态
    const [searchKeyword, setSearchKeyword] = useState<string | null>(null);
    const [isSearching, setIsSearching] = useState<boolean>(false);

    // 获取商品列表
    const fetchProducts = useCallback(async (limit: number = 20, cursor?: string) => {
        setLoading(true);
        setError(null);
        try {
            const result = await productService.getProducts(limit, cursor);
            setProducts(result.productList.products);
            setHasNext(result.productList.hasNext);
            setNextCursor(result.productList.nextCursor);
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '获取商品列表失败');
            console.error('获取商品列表失败:', err);
        } finally {
            setLoading(false);
        }
    }, []);

    // 获取更多商品（分页）
    const fetchMoreProducts = useCallback(async (limit: number = 20) => {
        if (!hasNext || !nextCursor) return;

        setLoading(true);
        setError(null);
        try {
            const result = await productService.getProducts(limit, nextCursor);
            setProducts(prev => [...prev, ...result.productList.products]);
            setHasNext(result.productList.hasNext);
            setNextCursor(result.productList.nextCursor);
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '加载更多商品失败');
            console.error('加载更多商品失败:', err);
        } finally {
            setLoading(false);
        }
    }, [hasNext, nextCursor]);

    // 根据关键词搜索商品
    const searchProducts = useCallback(async (keyword: string, limit: number = 20, cursor?: string) => {
        setIsSearching(true);
        setSearchKeyword(keyword);
        setLoading(true);
        setError(null);
        try {
            const result = await productService.fetchProductList(keyword, limit, cursor);
            // 如果是第一页搜索结果，替换列表；否则追加到列表
            if (!cursor) {
                setProducts(result.productList.products);
            } else {
                setProducts(prev => [...prev, ...result.productList.products]);
            }
            setHasNext(result.productList.hasNext);
            setNextCursor(result.productList.nextCursor);
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '搜索商品失败');
            console.error('搜索商品失败:', err);
            // 搜索失败时清空结果
            if (!cursor) {
                setProducts([]);
            }
        } finally {
            setLoading(false);
        }
    }, []);

    // 根据ID获取商品
    const fetchProductById = useCallback(async (id: number) => {
        setLoadingProduct(true);
        setError(null);
        try {
            const product = await productService.getProductById(id);
            setSelectedProduct(product);
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '获取商品详情失败');
            console.error('获取商品详情失败:', err);
        } finally {
            setLoadingProduct(false);
        }
    }, []);

    // 创建商品
    const createProduct = useCallback(async (input: CreateProductInput): Promise<boolean> => {
        setLoadingCreate(true);
        setError(null);
        try {
            const product = await productService.createProduct(input);
            // 将新创建的商品添加到列表开头
            setProducts(prev => [product, ...prev]);
            return true;
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '创建商品失败');
            console.error('创建商品失败:', err);
            return false;
        } finally {
            setLoadingCreate(false);
        }
    }, []);

    // 更新商品
    const updateProduct = useCallback(async (id: number, input: UpdateProductInput): Promise<boolean> => {
        setLoadingUpdate(true);
        setError(null);
        try {
            const product = await productService.updateProduct(id, input);
            // 更新商品列表中的商品
            setProducts(prev => prev.map(p => p.id === id ? product : p));
            // 如果当前选中的商品是被更新的商品，则更新选中商品
            if (selectedProduct && selectedProduct.id === id) {
                setSelectedProduct(product);
            }
            return true;
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '更新商品失败');
            console.error('更新商品失败:', err);
            return false;
        } finally {
            setLoadingUpdate(false);
        }
    }, [selectedProduct]);

    // 删除商品
    const deleteProduct = useCallback(async (id: number): Promise<boolean> => {
        setLoadingDelete(true);
        setError(null);
        try {
            const result = await productService.deleteProduct(id);
            if (result) {
                // 从商品列表中移除已删除的商品
                setProducts(prev => prev.filter(p => p.id !== id));
                // 如果当前选中的商品是被删除的商品，则清除选中
                if (selectedProduct && selectedProduct.id === id) {
                    setSelectedProduct(null);
                }
            }
            return result;
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '删除商品失败');
            console.error('删除商品失败:', err);
            return false;
        } finally {
            setLoadingDelete(false);
        }
    }, [selectedProduct]);

    // 选择商品
    const selectProduct = useCallback((product: Product | null) => {
        setSelectedProduct(product);
    }, []);

    // 清除选中商品
    const clearSelectedProduct = useCallback(() => {
        setSelectedProduct(null);
    }, []);

    // 刷新商品列表
    const refreshProducts = useCallback(async () => {
        await fetchProducts(20);
    }, [fetchProducts]);

    return (
        <ProductContext.Provider
            value={{
                products,
                selectedProduct,
                loading,
                loadingProduct,
                loadingCreate,
                loadingUpdate,
                loadingDelete,
                error,
                hasNext,
                nextCursor,
                fetchProducts,
                fetchMoreProducts,
                fetchProductById,
                createProduct,
                updateProduct,
                deleteProduct,
                selectProduct,
                clearSelectedProduct,
                refreshProducts,
                // 添加搜索相关属性
                searchProducts,
                searchKeyword,
                isSearching
            }}
        >
            {children}
        </ProductContext.Provider>
    );
};

export default ProductContext;
